
package com.bear.cmcc.NetTestHTTP.util;

import com.bear.cmcc.NetTestHTTP.NetworkTestApp;
import com.bear.cmcc.NetTestHTTP.R;
import com.bear.cmcc.NetTestHTTP.component.NetTestCellInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestConnecInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestLogBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestRoundInfoBean;
import com.bear.cmcc.NetTestHTTP.component.NetTestTimesInfoBean;
import com.bear.cmcc.NetTestHTTP.component.ServersConfigBean;
import com.bear.cmcc.NetTestHTTP.component.json.request.SubmitTestinfoRequest;
import com.bear.cmcc.NetTestHTTP.constant.FtpConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant;
import com.bear.cmcc.NetTestHTTP.constant.MyCommonConstant.PrivateActionName;
import com.bear.cmcc.NetTestHTTP.db.NetTestDBControl;
import com.bear.cmcc.NetTestHTTP.service.AutoTestService;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;

/**
 * 网络测试相关工具类。
 * 
 * @author suchangjun
 * @modify guanyh2013-2-27增加对其他服务是否启动的判断和通知服务的操作
 * @modify guanyh2013-2-28增加关闭、开启其他服务,增加getNetworkInfo、getLACCI方法，
 *         修改startNetTestService去掉actionname参数
 */
public class NetTestUtil {
    static String TAG = "NetTestUtil";

    static String GAP_CHAR = ",";

    /**
     * 启动网络测试服务。
     * 
     * @param context
     * @param timeNum 测试次数，如果是<0那么就无限制。
     * @param isFromAutoService 是否由定时任务触发。
     */
    public static void startNetTestService(Context context, int timeNum, boolean isFromAutoService) {
        // TODO
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.NET_TEST_SERVICENAME);
        intent.setClass(context, com.bear.cmcc.NetTestHTTP.service.NetTestService.class);
        Bundle bundle = new Bundle();
        bundle.putString(PrivateActionName.SERVICE_ACTION,
                PrivateActionName.SERVICE_ACTION_STARTSERVICE);
        bundle.putInt(PrivateActionName.NET_TEST_SERVICE_TESTNUM, timeNum);
        bundle.putBoolean(PrivateActionName.NET_TEST_SERVICE_IS_TIME, isFromAutoService);
        intent.putExtras(bundle);
        context.startService(intent);
    }

    /**
     * 开启自动测试
     * 
     * @param context
     */
    public static void startAutoNetTestService(Context context) {

        Intent intent = new Intent(context, AutoTestService.class);
        context.startService(intent);
    }

    /**
     * 关闭自动测试
     * 
     * @param context
     */
    public static void stopAutoNetTestService(Context context) {
        Intent intent = new Intent(context, AutoTestService.class);
        context.stopService(intent);
    }

    /**
     * 重新启动自动测试服务，主要是为修改定时任务计划时间。
     * 
     * @param context
     */
    public static void restartAutoNetTestService(Context context) {
        Intent intent = new Intent(context, AutoTestService.class);
        intent.setAction(MyCommonConstant.PrivateActionName.AUTO_RESET_TIME_GAP);
        context.startService(intent);

    }

    /**
     * 停止网络测试服务。
     * 
     * @param context
     */

    public static void stopNetTestService(Context context, int roundId) {
        // TODO
        sendServiceCommand(MyCommonConstant.PrivateActionName.NET_TEST_SERVICENAME,
                PrivateActionName.SERVICE_ACTION_STOPSERVICE, context,
                com.bear.cmcc.NetTestHTTP.service.NetTestService.class, roundId);

    }

    /**
     * 停止网络测试服务。
     * 
     * @param context
     */
    public static void stopNetTestService(Context context) {
        // TODO
        stopNetTestService(context, 0);
    }

    /**
     * 根据轮获取该轮下所有的次测试信息
     * 
     * @param context
     * @param roundInfoBeand 轮信息，根据这个信息获取该轮下所有的次测试信息。
     * @return ArrayList<NetTestInfoBean> 不为null，如果为null说明该轮下面没有测试。
     */
    public static ArrayList<NetTestTimesInfoBean> getNetTestTimesInfoByRound(Context context,
            NetTestRoundInfoBean roundInfoBeand) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestTimesInfoBean> result = new ArrayList<NetTestTimesInfoBean>();
        result = dbControl.queryTimesInfoByRoundID(String.valueOf(roundInfoBeand.getPID()));
        return result;
    }

    /**
     * 根据轮获取该轮下所有的次测试信息(上行)
     * 
     * @param context
     * @param roundInfoBeand 轮信息，根据这个信息获取该轮下所有的次测试信息。
     * @return ArrayList<NetTestInfoBean> 不为null，如果为null说明该轮下面没有测试。
     */
    public static ArrayList<NetTestTimesInfoBean> getNetTestTimesUpInfoByRound(Context context,
            NetTestRoundInfoBean roundInfoBeand) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestTimesInfoBean> result = new ArrayList<NetTestTimesInfoBean>();
        result = dbControl.queryUpTimesInfoByRoundID(String.valueOf(roundInfoBeand.getPID()));
        return result;
    }

    /**
     * 根据轮获取该轮下所有的次测试信息
     * 
     * @param context
     * @param _roundID 轮的ID
     * @return
     */
    public static ArrayList<NetTestTimesInfoBean> getNetTestTimesInfoByRound(Context context,
            int _roundID) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestTimesInfoBean> result = new ArrayList<NetTestTimesInfoBean>();
        result = dbControl.queryTimesInfoByRoundID(String.valueOf(_roundID));
        return result;
    }

    /**
     * 根据轮获取该轮下所有的次测试信息(上行)
     * 
     * @param context
     * @param _roundID 轮的ID
     * @return
     */
    public static ArrayList<NetTestTimesInfoBean> getNetTestTimesUpInfoByRound(Context context,
            int _roundID) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestTimesInfoBean> result = new ArrayList<NetTestTimesInfoBean>();
        result = dbControl.queryUpTimesInfoByRoundID(String.valueOf(_roundID));
        return result;
    }

    /**
     * 保存网络测试结果到本地数据库中。
     * 
     * @param context
     * @return 保存成功与否。
     */
    public static boolean saveNetTestInfo(Context context,
            ArrayList<NetTestTimesInfoBean> wantSaves, NetTestRoundInfoBean bach) {
        if (wantSaves == null || bach == null) {
            return false;
        }
        // TODO
        return true;
    }

    /**
     * 获取所有轮的测试信息
     * 
     * @param context
     * @param isNeedDelete 是否需要返回已经删除的信息，false只返回没删除的，true返回全量
     * @return ArrayList<NetTestBatchInfo> 如果为null，没有轮测试信息。
     */
    public static ArrayList<NetTestRoundInfoBean> getNetTestRoundsInfos(Context context,
            boolean isNeedDelete) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestRoundInfoBean> result = new ArrayList<NetTestRoundInfoBean>();
        result = dbControl.queryAllRoundInfo(isNeedDelete);
        return result;
    }

    /**
     * 根据pid获取轮的测试信息
     * 
     * @param context
     * @param pid 轮的pid.
     * @return NetTestRoundInfoBean 如果为null，没有轮测试信息。
     */
    public static NetTestRoundInfoBean getNetTestRoundsInfosBypid(Context context, int pid) {
        NetTestRoundInfoBean resultBean = null;
        try {
            NetTestDBControl dbControl;
            dbControl = new NetTestDBControl(context);
            ArrayList<NetTestRoundInfoBean> result = dbControl.queryAllRoundInfo(true);
            if (result != null) {
                for (NetTestRoundInfoBean element : result) {
                    if (pid == element.getPID()) {
                        resultBean = element;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultBean;
    }

    /**
     * 根据startTime获取轮的测试信息
     * 
     * @param context
     * @param startTime 轮的startTime.
     * @return NetTestRoundInfoBean 如果为null，没有轮测试信息。
     */
    public static NetTestRoundInfoBean getNetTestRoundsInfosByStartTime(Context context,
            String startTime) {
        try {
            NetTestDBControl dbControl;
            dbControl = new NetTestDBControl(context);
            NetTestRoundInfoBean result = dbControl.queryRoundInfoByStartTime(startTime);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据次测试bean来获取该次测试下所有小区信息
     * 
     * @param context
     * @param timesInfoBean
     * @return ArrayList<NetTestCellInfoBean>，如果为null说明该次下面没有小区信息
     */
    public static ArrayList<NetTestCellInfoBean> getNetTestCellInfosByTimes(Context context,
            NetTestTimesInfoBean timesInfoBean) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestCellInfoBean> result = new ArrayList<NetTestCellInfoBean>();
        result = dbControl.queryCellInfoBeanByTimesID(String.valueOf(timesInfoBean.getPID()));
        return result;
    }

    /**
     * 根据次测试bean来获取该次测试下所有小区信息
     * 
     * @param context
     * @param _timesID
     * @return ArrayList<NetTestCellInfoBean>，如果为null说明该次下面没有小区信息
     */
    public static ArrayList<NetTestCellInfoBean> getNetTestCellInfosByTimes(Context context,
            int _timesID) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestCellInfoBean> result = new ArrayList<NetTestCellInfoBean>();
        result = dbControl.queryCellInfoBeanByTimesID(String.valueOf(_timesID));
        return result;
    }

    /**
     * 根据pid来获取该次测试下所有小区信息
     * 
     * @param context
     * @param _roundID 轮的组件。
     * @return ArrayList<NetTestCellInfoBean>，如果为null说明下面没有小区信息
     */
    public static ArrayList<NetTestCellInfoBean> getNetTestCellInfosByPid(Context context,
            int _roundID) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        ArrayList<NetTestCellInfoBean> result = new ArrayList<NetTestCellInfoBean>();
        ArrayList<NetTestTimesInfoBean> times = dbControl.queryTimesInfoByRoundID(_roundID + "");
        if (times != null) {
            for (NetTestTimesInfoBean element : times) {
                result.addAll(dbControl.queryCellInfoBeanByTimesID(element.getPID() + ""));
            }
        }
        dbControl = null;
        return result;
    }

    /**
     * 根据timeid、lac和ci判断是否已经插入过这条小区记录了
     * 
     * @param context
     * @param _timesID
     * @return boolean
     */
    public static boolean hasNetTestCellInfosByTimes(Context context, int _timesID, int _lac,
            int _ci) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);

        return dbControl.hasCellInfoBeanByTimesID(String.valueOf(_lac), String.valueOf(_ci),
                String.valueOf(_timesID));
    }

    /**
     * 根据小区bean获取小区接通率
     * 
     * @param context
     * @param cellInfoBean
     * @return
     */
    public double getCellConnectPercent(Context context, NetTestCellInfoBean cellInfoBean) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        return dbControl.queryCellConnectPercent(cellInfoBean.getLac(), cellInfoBean.getCi());
    }

    /**
     * 根据小区bean获取小区掉线率
     * 
     * @param context
     * @param cellInfoBean
     * @return
     */
    public double getCellDropPercent(Context context, NetTestCellInfoBean cellInfoBean) {
        NetTestDBControl dbControl;
        dbControl = new NetTestDBControl(context);
        return dbControl.queryCellDropPercent(cellInfoBean.getLac(), cellInfoBean.getCi());
    }

    /**
     * 保存本轮网络测试结果到本地数据库中。
     * 
     * @param context
     * @return 保存成功与否。
     */
    public static boolean saveNetTestBatchInfo(Context context, NetTestRoundInfoBean wantSave) {
        if (wantSave == null) {
            return false;
        }
        // TODO
        return true;
    }

    /**
     * 判断其他服务是否启动
     * 
     * @param context
     * @param serviceName like
     *            com.funo.networktesttassistant.service.NetTestService
     * @return service是否启用。
     */
    public static boolean serviceIsWorked(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
                .getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            String name = runningService.get(i).service.getClassName().toString();
            if (name.equalsIgnoreCase(serviceName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 通知其他service操作的方法
     * 
     * @param serviceName like
     *            com.funo.networktesttassistant.service.NetTestService
     * @param command 操作命令
     * @param context
     * @param service类
     * @return 网络是否可以使用。
     */
    public static void sendServiceCommand(String serviceName, String command, Context context,
            Class tclass, int roundId) {
        Intent intent = new Intent(serviceName);
        intent.setClass(context, tclass);
        Bundle bundle = new Bundle();
        bundle.putString(PrivateActionName.SERVICE_ACTION, command);
        bundle.putInt(PrivateActionName.SERVICE_ACTION_ROUND_ID, roundId);
        intent.putExtras(bundle);
        context.startService(intent);
    }

    /**
     * 关闭其他的服务(AutoTestService 这个服务不能停止)
     * 
     * @param context
     * @param ourServices 传递过来的service集合
     */
    public static ArrayList<String> stopOtherService(Context context, ServiceInfo[] ourServices,
            Class classes) {
        ArrayList<String> stopedServicesName = new ArrayList<String>();
        for (int i = 0; i < ourServices.length; i++) {
            ServiceInfo tempSInfo = ourServices[i];
            // AutoTestService 这个服务不能停止，只是一个计划服务，没有任何下载功能，不会有占带宽情况
            if (tempSInfo.name.equalsIgnoreCase(AutoTestService.class.getName())) {
                continue;
            }

            if (!tempSInfo.name.equalsIgnoreCase(classes.getName()))// 如果不是传入的类名
            {
                boolean working = NetTestUtil.serviceIsWorked(context, tempSInfo.name);// 如果服务在运行，暂停该服务
                if (working) {
                    Intent intent = null;
                    try {
                        intent = new Intent(context, (Class.forName(tempSInfo.name)));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (intent != null) {
                        context.stopService(intent);
                        stopedServicesName.add(tempSInfo.name);
                    }
                }
            }
        }
        return stopedServicesName;
    }

    /**
     * 开启之前关闭过的其他的服务
     * 
     * @param context
     * @param stopedServicesName 之前停止过的servicename集合
     * @param ourServices 传递过来的service集合
     */
    public static void startOtherService(Context context, ArrayList<String> stopedServicesName,
            ServiceInfo[] ourServices) {
        for (int i = 0; i < stopedServicesName.size(); i++) {
            for (int j = 0; j < ourServices.length; j++) {
                ServiceInfo tempSInfo = ourServices[i];
                if (tempSInfo.name.equalsIgnoreCase(stopedServicesName.get(i).toString())) {
                    Intent intent = null;
                    try {
                        intent = new Intent(context, (Class.forName(tempSInfo.name)));
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (intent != null) {
                        context.startService(intent);
                    }
                }
            }
        }
    }

    /**
     * 获取当前网络类型及相关信息
     * 
     * @param context
     * @return fqsize
     */
    public static int getNetworkInfo(Context context, NetTestLogBean netLogBean) {
        try {
            // ArrayList<String> infos = new ArrayList<String>();
            int fqsize = 0;
            ConnectivityManager conMan = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = conMan.getActiveNetworkInfo();
            String typeName = networkInfo.getTypeName();
            if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.MOBILE)) {
                netLogBean.setNetType(networkInfo.getSubtypeName());
                netLogBean.setNetName(networkInfo.getExtraInfo());
                if (networkInfo.getSubtypeName().equalsIgnoreCase(MyCommonConstant.NET_TYPE.EDGE)
                        || networkInfo.getSubtypeName().equals(MyCommonConstant.NET_TYPE.GPRS)) {
                    fqsize = MyCommonConstant.FQSIZE.SIZE_2G;
                } else {
                    fqsize = MyCommonConstant.FQSIZE.SIZE_TD;
                }
            }
            if (typeName.equalsIgnoreCase(MyCommonConstant.NET_NAME.WIFI)) {
                WifiManager wifiManager = (WifiManager) context
                        .getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                netLogBean.setNetType(MyCommonConstant.NET_TYPE.WLAN);
                netLogBean.setNetName(wifiInfo.getSSID());
                fqsize = MyCommonConstant.FQSIZE.SIZE_WLAN;
                netLogBean.setWifiStrong(String.valueOf(wifiInfo.getRssi()));
                // infos.add(wifiInfo.getMacAddress());
                netLogBean.setWifiBSSID(wifiInfo.getBSSID());
            }
            return fqsize;
        } catch (Exception e) {
            return MyCommonConstant.FQSIZE.SIZE_2G;
        }
    }

    /**
     * 获取运营商国家代码，运营商网络代码，坐标，cellid,msisdn,imsi,imei
     * 
     * @param TelephonyManager
     * @return 0-mcc 1-mnc 2-lac 3-ci 4-msisdn 5-imsi 6-imei
     */
    public static void getLACCI(Context context, NetTestLogBean netLogBean) {
        try {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(context.TELEPHONY_SERVICE);
            CellLocation sm = tm.getCellLocation();
            if (sm == null)
                return;

            if (sm instanceof GsmCellLocation) {
                GsmCellLocation gsm = (GsmCellLocation) sm;
                netLogBean.setLac(gsm.getLac());
                netLogBean.setCi(gsm.getCid());
            } else if (sm instanceof CdmaCellLocation) {
                CdmaCellLocation cdma = (CdmaCellLocation) sm;
                netLogBean.setLac(cdma.getNetworkId());
                netLogBean.setCi(cdma.getBaseStationId());
            }

            netLogBean.setMcc(Integer.parseInt(tm.getNetworkOperator().substring(0, 3)));
            netLogBean.setMnc(Integer.parseInt(tm.getNetworkOperator().substring(3, 5)));

            String temp = tm.getLine1Number();
            String msisdn;
            try {
                if (temp.length() >= 11) {
                    msisdn = temp.substring(temp.length() - 11, temp.length());
                } else {
                    msisdn = "";
                }

                if (msisdn == null || msisdn.trim().equalsIgnoreCase("")) {
                    msisdn = SetUtil.getTelNumber(context);
                }
                netLogBean.setMsisdn(msisdn);
            } catch (Exception ex) {
                netLogBean.setMsisdn("");
            }
            netLogBean.setImsi(tm.getSubscriberId());
            netLogBean.setImei(tm.getDeviceId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断小区是否发生改变
     * 
     * @param cellLocation
     * @param lac
     * @param ci
     * @return
     */
    public static boolean isCellChange(CellLocation cellLocation, int lac, int ci) {
        try {
            GsmCellLocation sm = ((GsmCellLocation) cellLocation);
            if (sm == null)
                return false;

            int templac = sm.getLac();
            int tempci = sm.getCid();
            if (lac == 0)
                lac = sm.getLac();
            if (ci == 0)
                ci = sm.getCid();
            if (templac == lac && tempci == ci)
                return false;
            else
                return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 当前的log数据
     * 
     * @return String log数据
     */
    public static String getLog(Context context, NetTestLogBean netLogBean) {
        StringBuilder log = new StringBuilder();
        netLogBean.setlogTime(MyCommonUtil.getCurDate());
        netLogBean.setDevice(MyCommonUtil.getDeviceByMD5(MyCommonUtil.getDeviceId(context)));
        netLogBean.setModel(Build.MODEL);
        netLogBean.setlogFileName(netLogBean.getDevice() + "@" + netLogBean.getlogTime());
        netLogBean.setLatitude(String.valueOf(NetworkTestApp.getApp().getLatitude()));
        netLogBean.setLongitude(String.valueOf(NetworkTestApp.getApp().getLongitude()));
        netLogBean.setCity(NetworkTestApp.getApp().getCityName());

        log.append(netLogBean.getlogTime());
        log.append(GAP_CHAR);
        log.append(netLogBean.getDevice());
        log.append(GAP_CHAR);
        log.append(netLogBean.getModel());
        log.append(GAP_CHAR);
        log.append(netLogBean.getNetType());
        log.append(GAP_CHAR);
        log.append(netLogBean.getNetName());
        log.append(GAP_CHAR);
        log.append(netLogBean.getMcc());
        log.append(GAP_CHAR);
        log.append(netLogBean.getMnc());
        log.append(GAP_CHAR);
        log.append(netLogBean.getLac());
        log.append(GAP_CHAR);
        log.append(netLogBean.getCi());
        log.append(GAP_CHAR);
        log.append(String.format("%.2f", netLogBean.getOneLogAveragespeed()));
        log.append(GAP_CHAR);
        log.append(netLogBean.getReplyCode());
        log.append(GAP_CHAR);
        log.append(netLogBean.getOneLogfileSize());
        log.append(GAP_CHAR);
        log.append(netLogBean.getOneLogDownloadTime());
        log.append(GAP_CHAR);
        log.append(netLogBean.getNetStrong());
        log.append(GAP_CHAR);
        log.append(netLogBean.getWifiStrong());
        log.append(GAP_CHAR);
        log.append(netLogBean.getWifiBSSID());
        log.append(GAP_CHAR);
        log.append(GAP_CHAR);
        log.append(GAP_CHAR);
        log.append(GAP_CHAR);
        log.append(netLogBean.getMsisdn());
        log.append(GAP_CHAR);
        log.append(netLogBean.getImsi());
        log.append(GAP_CHAR);
        log.append(netLogBean.getImei());
        log.append(GAP_CHAR);
        log.append(netLogBean.getAPMAC());
        log.append(GAP_CHAR);
        log.append(netLogBean.getCity());
        log.append(GAP_CHAR);
        log.append(netLogBean.getIpAddress());
        log.append(GAP_CHAR);
        log.append(netLogBean.getCostTime());
        log.append(GAP_CHAR);
        log.append(netLogBean.getMaxSpeed());
        log.append(GAP_CHAR);
        log.append(netLogBean.getMinSpeed());
        log.append(GAP_CHAR);
        log.append(netLogBean.getServiceName());
        log.append(GAP_CHAR);
        log.append(netLogBean.getLatitude());
        log.append(GAP_CHAR);
        log.append(netLogBean.getLongitude());

        return log.toString();
    }

    /**
     * 读取文件中的数据并包装成 SubmitTestinfoRequest数组对象。
     * 
     * @param file 可以是文件夹或者文件，如果是文件夹那么就直接上传这个文件夹下面的文件。
     * @return ArrayList<SubmitTestinfoRequest>对象不会为null。
     * @see #getLog(Context, NetTestLogBean)
     */
    public static ArrayList<SubmitTestinfoRequest> changeFileToSubmitObject(File file,
            Context context) {
        ArrayList<SubmitTestinfoRequest> allSubmit = new ArrayList<SubmitTestinfoRequest>();
        SubmitTestinfoRequest submitObject = null;
        try {
            ArrayList<File> wantUpFile = new ArrayList<File>();
            if (file.isDirectory()) {
                for (File element : file.listFiles()) {
                    if (element != null && (element.length() > 0) && element.isFile()) {
                        wantUpFile.add(element);
                    }
                }
            } else {
                if (file.length() > 0) {
                    wantUpFile.add(file);
                }
            }

            FileReader fr = null;
            BufferedReader buff = null;
            String text = null;
            String[] temp = null;
            int length = 0;
            String imdiMd5 = MyCommonUtil.getDeviceByMD5(MyCommonUtil.getDeviceId(context));
            for (File upFile : wantUpFile) {
                try {
                    fr = new FileReader(upFile);
                    buff = new BufferedReader(fr);
                    text = null;
                    while ((text = buff.readLine()) != null) {
                        temp = text.split(GAP_CHAR);
                        length = temp.length;
                        if (temp != null && temp.length > 0) {
                            try {
                                submitObject = new SubmitTestinfoRequest();
                                // 这个顺序和getLog(Context, NetTestLogBean) 中保存顺序一致。
                                submitObject.setTestTime(temp[0]);
                                submitObject.setIMEI(imdiMd5);// 用imdi 的md5加密
                                submitObject.setDeviceType(temp[2]);
                                submitObject.setNetType(temp[3]);
                                submitObject.setNetName(temp[4]);
                                submitObject.setMCC(temp[5]);
                                submitObject.setMNC(temp[6]);
                                submitObject.setLAC(temp[7]);
                                submitObject.setCI(temp[8]);
                                submitObject.setAverageSpeed(temp[9]);
                                submitObject.setTestResult(temp[10]);
                                // 11点是下载文件大小，新街口不需上传这个参数
                                submitObject.setCostTime(temp[12]);
                                submitObject.setSingnalStrenth(temp[13]);
                                submitObject.setWifi_singnalStrenth(temp[14]);
                                submitObject.setWifi_bssid(temp[15]);
                                // 14 15 分别是wifi强度 wifissid 16 17 18 都是空的
                                submitObject.setMSISDN(temp[19]);
                                submitObject.setIMSI(temp[20]);
                                // submitObject.setIMEI(temp[21]);
                                // 有可能版本升级的时候，旧数据还没有上传，就数据没有这么长
                                if (length > 22) {
                                    submitObject.setAPMAC(temp[22]);
                                    submitObject.setCity(temp[23]);
                                    submitObject.setIPAdd(temp[24]);
                                    submitObject.setCostTime(temp[25]);
                                    submitObject.setMaxSpeed(temp[26]);
                                    submitObject.setMinSpeed(temp[27]);
                                    submitObject.setServerName(temp[28]);
                                    submitObject.setLat(temp[29]);
                                    submitObject.setLon(temp[30]);
                                }

                                allSubmit.add(submitObject);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return allSubmit;
    }

    /**
     * 保存log日志到本地
     */
    public static void saveLog(Context context, NetTestLogBean netLogBean) {
        String logStr = getLog(context, netLogBean);
        File fileDir = context.getFilesDir();
        File dirfj = new File(fileDir + FtpConstant.FtpFileNames.logsaveaddressfj);
        String localLogPathFJ = fileDir.getAbsolutePath()
                + FtpConstant.FtpFileNames.logsaveaddressfj + netLogBean.getlogFileName();
        File filefj = new File(localLogPathFJ);
        FileOutputStream fos = null;
        BufferedOutputStream buff = null;
        try {
            if (!dirfj.exists()) {
                dirfj.mkdirs();
            }
            if (filefj.exists()) {
                logStr = "\n" + logStr;
            }
            fos = new FileOutputStream(filefj, true);
            buff = new BufferedOutputStream(fos);
            buff.write(logStr.getBytes());
            buff.flush();
        } catch (IOException e) {
            Log.d(TAG, TAG + " saveLog Exception: " + e.getMessage());
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (buff != null) {
                    buff.close();
                }
            } catch (IOException e) {
                Log.d(TAG, TAG + " saveLog finally close IOException: " + e.getMessage());
            }
        }
    }

    /**
     * 插入数据到小区表
     * 
     * @param _averageSpeed
     * @param _maxSpeed
     * @param _minS
     * @param _lac
     * @param _ci
     * @param _cellName
     * @param _maxStrong
     * @param _minStrong
     * @param _timeid
     * @param context
     * @param netLogBean
     */
    public static void insertCellInfo(double _averageSpeed, double _maxSpeed, double _minS,
            int _maxStrong, int _minStrong, int _timeid, Context context, NetTestLogBean netLogBean) {
        try {
            NetTestCellInfoBean cellInfoBean = new NetTestCellInfoBean();
            NetTestDBControl dbControl = new NetTestDBControl(context);
            cellInfoBean.setAverageSpeed(_averageSpeed);
            cellInfoBean.setMaxSpeed(_maxSpeed);
            cellInfoBean.setMinSpeed(_minS);
            cellInfoBean.setLac(netLogBean.getLac());
            cellInfoBean.setCi(netLogBean.getCi());
            cellInfoBean.setCellName(dbControl.getCellName(context, netLogBean.getLac(),
                    netLogBean.getCi(), netLogBean.getNetType()));
            cellInfoBean.setMaxNetStrong(_maxStrong);
            cellInfoBean.setMinNetStrong(_minStrong);
            cellInfoBean.setTimesID(_timeid);
            dbControl.insertToTestCellInfo(cellInfoBean);
        } catch (Exception ex) {
            Log.d(TAG, "insertCellInfo Exception=>" + ex.getMessage());
        }
    }

    /**
     * 插入数据到times表
     * 
     * @param testInfoBean
     * @param context
     */
    public static void insertTimesInfo(NetTestTimesInfoBean testInfoBean, Context context) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        dbControl.insertToTestTimesInfo(testInfoBean);
    }

    /**
     * 插入数据到round表
     * 
     * @param roundInfoBean
     * @param context
     */
    public static void insertRoundInfo(NetTestRoundInfoBean roundInfoBean, Context context) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        dbControl.insertToTestRoundInfo(roundInfoBean);
    }

    /**
     * 更新数据到round表
     * 
     * @param roundInfoBean
     * @param context
     */
    public static void updateOrCreateTestRoundInfo(NetTestRoundInfoBean roundInfoBean,
            Context context) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        dbControl.updateOrCreateTestRoundInfo(roundInfoBean);
    }

    /**
     * 插入数据到connect表
     * 
     * @param connectInfoBean
     * @param context
     */
    public static void insertConnectInfo(NetTestConnecInfoBean connectInfoBean, Context context,
            NetTestLogBean netLogBean) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        connectInfoBean.setLac(netLogBean.getLac());
        connectInfoBean.setCi(netLogBean.getCi());
        dbControl.insertToTestConnectInfo(connectInfoBean);
    }

    /**
     * 发送测试过程中的速度广播
     * 
     * @param _averageSpeed 平均速度，应该是轮的平均速度。
     * @param _maxSpeed
     * @param _minSpeed
     * @param context
     */
    public static void sendNetTestSpeedBroad(double _averageSpeed, double _maxSpeed,
            double _minSpeed, String flag, Context context) {
        try {

            Intent intent = new Intent(MyCommonConstant.PrivateActionName.NET_TEST_SPEED_BROAD);
            intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_AVERAGE_SPEED_BROAD,
                    _averageSpeed+"");
            intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_MAX_SPEED_BROAD, _maxSpeed+"");
            intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_MIN_SPEED_BROAD, _minSpeed+"");
            intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_FORWARD, flag);
            context.sendBroadcast(intent);
            // Log.i(TAG, "sendNetTestSpeedBroad ");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 一次测试结束发送广播
     * 
     * @param context
     */
    public static void setOneTimesFinishBroad(Context context, int currentTime, boolean isSuccess) {
        Intent intent = new Intent(
                MyCommonConstant.PrivateActionName.NET_TEST_ONE_TIME_FINISH_BROAD);
        intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_CURRENT_TIME, currentTime);
        intent.putExtra(MyCommonConstant.PrivateActionName.NET_TEST_CURRENT_TIME_IS_SUCCESS,
                isSuccess);
        context.sendBroadcast(intent);
    }

    /**
     * 一轮测试结束发送广播
     * 
     * @param context
     */
    public static void setOneRoundFinishBroad(Context context) {
        Intent intent = new Intent(
                MyCommonConstant.PrivateActionName.NET_TEST_ONE_ROUND_FINISH_BROAD);
        context.sendBroadcast(intent);
    }

    /**
     * 一轮测试结束发送广播
     * 
     * @param context
     */
    public static void setOneRoundBeginBroad(Context context) {
        Intent intent = new Intent(
                MyCommonConstant.PrivateActionName.NET_TEST_ONE_ROUND_BEGIN_BROAD);
        context.sendBroadcast(intent);
    }

    /**
     * 手动停止测试发广播
     * 
     * @param context
     */
    public static void setStopServiceBroad(Context context) {
        Intent intent = new Intent(MyCommonConstant.PrivateActionName.NET_TEST_STOP_SERVICE_BROAD);
        context.sendBroadcast(intent);
    }

    /**
     * 分享本轮测试信息（根据pid）
     * 
     * @param context
     * @param pid
     */
    public static void shareNetTestRoundInfo(Context context, int pid) {
        NetTestRoundInfoBean value = NetTestUtil.getNetTestRoundsInfosBypid(context, pid);
        shareNetTestRoundInfo(context, value);

    }

    /**
     * 分享本轮测试信息。
     * 
     * @param context
     */
    public static void shareNetTestRoundInfo(Context context, NetTestRoundInfoBean bean) {
        if (bean != null) {

            String title = context.getString(R.string.share);
            String shareMessasge = String.format(context.getString(R.string.share_round_message),
                    MyCommonUtil.getFormatString(bean.getAverageSpeed()),
                    MyCommonUtil.getFormatString(bean.getMaxSpeed()),
                    MyCommonUtil.getFormatString(bean.getMinSpeed()), bean.getTestTimes(),
                    bean.getStartTime() + "--" + bean.getEndTime());
            MyCommonUtil.share(context, title, shareMessasge);
        }
    }

    /**
     * 删除round表某条记录
     * 
     * @param context
     * @param roundInfoBean
     */
    public static void deleteRoundInfo(Context context, NetTestRoundInfoBean roundInfoBean) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        dbControl.deleteRoundInfo(roundInfoBean.getPID());
    }

    /**
     * 删除round表某条记录
     * 
     * @param context
     * @param roundInfoBean
     */
    public static void deleteRoundInfo(Context context, int _roundID) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        dbControl.deleteRoundInfo(_roundID);
    }

    /**
     * 开启log上传服务
     * 
     * @param context
     */
    public static void startUploadLogService(Context context) {
        sendServiceCommand(MyCommonConstant.PrivateActionName.NET_SPEED_LOG_UPLOAD_SERVICENAME,
                PrivateActionName.SERVICE_ACTION_STARTSERVICE, context,
                com.bear.cmcc.NetTestHTTP.service.NetSpeedLogUpLoadService.class, 0);
    }

    /**
     * 返回服务器配置
     * 
     * @param context
     * @return
     */
    public static ServersConfigBean getServerBean(Context context) {
        ServersConfigBean serverConfigBean = null;
        serverConfigBean = SetUtil.getServersConfigBean(context);
        if (serverConfigBean == null) {
            serverConfigBean = new ServersConfigBean();
            serverConfigBean.setDownloaddictory(FtpConstant.ComFtp500Config.downDictory500);
            serverConfigBean.setDownloadName(FtpConstant.ComFtp500Config.hostname500);
            serverConfigBean.setDownloadPwd(FtpConstant.ComFtp500Config.passDownload500);
            serverConfigBean.setServerAddress(FtpConstant.ComFtp500Config.host500);
            serverConfigBean.setServerName(FtpConstant.ComFtp500Config.userDownload500);
            serverConfigBean.setServerPort(FtpConstant.ComFtp500Config.hostport500);
            SetUtil.setServersConfigBean(serverConfigBean, context);
        }
        return serverConfigBean;
    }

    // /**
    // * 传入最大最小值，计算抖动强度
    // *
    // * @param _maxSpeed
    // * @param _minSpeed
    // * @return
    // */
    // public static String getWaveShakeStrong(double _maxSpeed, double
    // _minSpeed) {
    // try {
    // return MyCommonUtil.getFormatString(((_maxSpeed < 0) ? (_maxSpeed * -1) :
    // _maxSpeed)
    // - ((_minSpeed < 0) ? (_minSpeed * -1) : _minSpeed));
    // } catch (Exception e) {
    // return "";
    // }
    // }

    /**
     * 传入最大最小值，计算抖动强度
     * 
     * @param _maxSpeed
     * @param _minSpeed
     * @return
     */
    public static String getWaveShakeStrong(Context context, int roundId) {
        try {
            ArrayList<NetTestTimesInfoBean> times = getNetTestTimesInfoByRound(context, roundId);
            if (times != null) {
                int size = times.size();
                int count = 0;
                double allWave = 0;
                for (int i = 0; i < size; i++) {
                    if (times.get(i) != null) {
                        count++;
                        allWave = allWave + times.get(i).getWaveShakeStrongDouble();
                    }
                }

                return MyCommonUtil.getFormatString((allWave / count));

            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 根据小区lac和ci获取小区接通率
     * 
     * @param context
     * @param _lac
     * @param _ci
     * @return 直接返回百分比 如78%
     */
    public static String getCellConnectPercent(Context context, int _lac, int _ci) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        double connectPercent = dbControl.queryCellConnectPercent(_lac, _ci);
        NumberFormat nFromat = NumberFormat.getPercentInstance();
        return nFromat.format(connectPercent);
    }

    /**
     * 根据小区lac和ci获取小区接通率
     * 
     * @param context
     * @param _lac
     * @param _ci
     * @return 直接返回百分比 如78%
     */
    public static String getCellDropPercent(Context context, int _lac, int _ci) {
        NetTestDBControl dbControl = new NetTestDBControl(context);
        double connectPercent = dbControl.queryCellDropPercent(_lac, _ci);
        NumberFormat nFromat = NumberFormat.getPercentInstance();
        return nFromat.format(connectPercent);
    }

    /**
     * 轮测试过程，手动停止，会产生一个费数据，这边要清理一次。
     * 
     * @param context
     * @param roundId
     */
    public static void clearbadData(Context context, int roundId) {
        if (roundId > 0 && context != null) {
            // 先不动这边数据
        }

    }

}
